package cn.lzg.client;

import cn.lzg.client.scanner.Invoker;
import cn.lzg.client.scanner.InvokerHoler;
import cn.lzg.common.core.model.Response;
import cn.lzg.common.core.session.SessionImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ClientHandler extends SimpleChannelInboundHandler<Response> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception {
		handlerMessage(new SessionImpl(ctx.channel()), msg);
	}

	private void handlerMessage(SessionImpl session, Response response) {
		Short socketmodule = response.getModule();
		Short socketcmd = response.getCmd();
		int stateCode = response.getStateCode();
		/**
		 * 获取命令执行器
		 */
		System.out.println(socketmodule + " " + socketcmd);
		Invoker invoker = InvokerHoler.getInvoker(socketmodule, socketcmd);
		if (invoker != null) {
			try {
				invoker.invoker(stateCode, response.getData());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// 找不到执行器
			System.out.println(String.format("module:%s  cmd:%s 找不到命令执行器", response.getModule(), response.getCmd()));
		}
	}

	/**
	 * 断开连接
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// 断开连接
		System.out.println("连接成功");
	}
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("断开连接");
	}
}
